## R Code for Replication: Main Text
# Electoral Dis-connection: The Limits of Re-Election in Contexts of Weak Accountability
# Julie Anne Weaver
# Journal of Politics


###############################################################
####### Descriptive Stats from Survey (Sub-Section Title: Corruption and Increasing Malfeasance in a Second Term)
##############################################################

# Dataset: survey.data

#########################
# Question: How big of a problem is corruption in the management of the municipal government compared to other problems?
# Responses: 65% said it was the biggest problem, and 86.3% said it was either a big or the biggest problem.
#########################

## answers:
# 1 = not a problem
# 2 = small problem
# 3 = big problem but not the biggest
# 4 = biggest problem

prop.table(table(survey.data$corruption.prob))
# 1           2           3           4 
# 0.009137056 0.127918782 0.213197970 0.649746193

0.213197970 + 0.649746193 # 0.8629442


######################### Question: If a mayor does a good job and is re-elected, 
# how likley is it he/she will do a good job in a second term?
# response: Only 40% said good performance was ‘likely’ or ‘very likely’ to be repeated. 

## answer options
# -99 = Don't know
# -97 = no response
# 1 = very likely
# 2 = likely
# 3 = depends
# 4 = unlikely
# 5 = very unlikely 

prop.table(table(survey.data$repeat.good.perf))
#     -99         -97           1           2           3           4           5 
# 0.011310085 0.004712535 0.144203582 0.261074458 0.229029218 0.218661640 0.131008483 
0.144203582 + 0.261074458 # 40.53%

######################### Question: Those who answered ‘unlikely’ or ‘very unlikely’ were then asked ‘why’...

# Responses: More than half (53.4%) said re-elected mayors are more likely to be corrupt 
#because they learn how to be corrupt in their first period. 
prop.table(table(survey.data$norepeat.learncorrupt)) 
#    0         1 
# 0.4663073 0.5336927

# Responses: Almost a quarter (23.5%) reported that there is not sufficient oversight 
#to ensure re-elected mayors will do a good job in a second term.
prop.table(table(survey.data$norepeat.nooversight))  
#     0         1 
# 0.7654987 0.2345013 



###############################################################
####### RDD (Section Title: The Incumbency Disadvantage in Mayoral Politics)
##############################################################

# dataset name: RDD.data

## Run the RDD

# dependent variable = won
# forcing variable =  "margin.voteshare.prev"

library(rdrobust)

rdd.1 <- rdrobust(y=RDD.data$won, x=RDD.data$margin.voteshare.prev, 
                  cluster=RDD.data$UbigeoJNE)
summary(rdd.1)
## RDD estimate: -0.241
## p value 0.000 

################
################ Figure 1: RDD Plot
################

rdplot(y=RDD.data$won, x=RDD.data$margin.voteshare.prev, kernel="uni",
       x.label="Voteshare Margin in Previous Election", y.label="Likelihood of Winning Current Election", 
       title="",
       binselect="es")


###############################################################
####### Conjoint Results (Section Title: Preferring Challengers Despite Good Performance)
##############################################################


################
################ Descriptive stats from original survey
################

# dataset used:  survey.data

################ Question: How important are the following possible responsibilities of the mayor?
### answer options:
# 1 = very important
# 2 = important
# 3 = not important
# 4 = not a responsibility
# -99 = don't know
# -97 = no response

################ Construct public works projects (for example, build a bridge or irrigation system, or improve streets)
## reponse: 95.6% described it as a very important or important responsibility of mayors
prop.table(table(survey.data$responsibility.pw))
#   -99         -97           1           2           3           4 
# 0.010367578 0.009425071 0.440150801 0.515551367 0.019792648 0.004712535
0.440150801 + 0.515551367 # = 0.9557022

################ Provide individual financial assistance in case of an emergency
## reponse: 80.3% of respondents described providing this kind of aid as a very important or important responsibility of mayors

prop.table(table(survey.data$responsibility.finaid))
#   -99        -97          1          2          3          4 
# 0.01602262 0.01508011 0.21206409 0.59095193 0.08765316 0.07822809 
0.21206409 + 0.59095193 # = 0.803016


################
################ Figure 2: Effect Sizes of Candidate Traits on Probability of Receiving Respondents’ Vote
################

# dataset used:  conjoint.data

library("cjoint")


## set the baseline levels for each attribute:

baselines <- list()
baselines$feat.gender <- "male"
baselines$feat.incumbent <- "Challenger"         
baselines$feat.soc.orgs <- "No"
baselines$feat.village <- "Village 2 hours away"
baselines$feat.work <- "Farmer"
baselines$feat.lang <- "Spanish"
baselines$feat.dynasty <- "Uncle was mayor"
baselines$feat.gifts <- "Never gives gifts at campaign events"

############### setting the weights in cjoint
# i.e. because not every attribute has an equal probability of appearing to respondents

### set attribute levels:
attribute_list <- list()
attribute_list[["feat.gender"]] <-c("female", "male")
attribute_list[["feat.incumbent"]] <-c("Incumbent - no performance info", "Incumbent - good performance - public works",
                                       "Incumbent - good performance - fin aid", "Incumbent - bad performance - fin aid",      
                                       "Incumbent - bad performance - public works", "Challenger")
attribute_list[["feat.soc.orgs"]] <-c("No", "Yes")
attribute_list[["feat.village"]] <-c("Village 2 hours away", "Same village")
attribute_list[["feat.work"]] <-c("Business owner", "Farmer")
attribute_list[["feat.lang"]] <-c("Spanish", "Quechua")
attribute_list[["feat.dynasty"]] <-c("First in family to run", "Uncle was mayor")
attribute_list[["feat.gifts"]] <-c("Gives gifts at campaign events", "Never gives gifts at campaign events")

###### set the probability of each attribute value being randomly generated

marginal_weights <- list() # Uniform for all except gender and incumbency - i.e. probability of each value within the trait is equal
marginal_weights[["feat.gender"]] <- c(1/3, 2/3) # female has only 1/3 prob 
marginal_weights[["feat.incumbent"]] <- c(1/10, 1/10, 1/10, 1/10, 1/10, 1/2) # challenger has 50% prob, all others 10%
### all the other attributes have 50% chance of being selected (always only 2 attribute levels, each with equal probability)
marginal_weights[["feat.soc.orgs"]] <-c(1/2, 1/2)
marginal_weights[["feat.village"]] <- c(1/2, 1/2)
marginal_weights[["feat.work"]] <- c(1/2, 1/2)
marginal_weights[["feat.lang"]] <- c(1/2, 1/2)
marginal_weights[["feat.dynasty"]] <- c(1/2, 1/2)
marginal_weights[["feat.gifts"]] <- c(1/2, 1/2)

### use makeDesign to set the weights

conj.design.reweight <- makeDesign(type="constraints", attribute.levels=attribute_list,
                                   level.probs=marginal_weights)

#### Estimate AMCE
### note add 'design = conj.design.reweight' into the amce formula

amce1 <- amce(outcome_votechoice_binary ~ feat.gender + feat.incumbent          
              + feat.soc.orgs + feat.village + feat.work                
              + feat.lang  + feat.dynasty + feat.gifts, data=conjoint.data,
              cluster=TRUE, respondent.id="respondentID", design=conj.design.reweight,
              baselines=baselines)
summary(amce1)
# Note: Estimates shown in Table F.3: Average Marginal Component Effects (AMCE)

## plot:

plot(amce1, xlab="Change in Probability of Voting for a Candidate for Mayor",
     breaks=c(-.2, 0, .2), labels=c("-.2","0",".2"), text.size=10,
     label.baseline = TRUE, plot.display="all", 
     attribute.names=c("Political Dynasty", "Gender", "Gifts in Campaign",
                       "Incumbency Status", "Ethnicity/First Language",
                       "Social Organizations", "Village", "Work/Wealth")) 


################
################ Figure 3: Conjoint Results Conditional on Respondents’ Reported Likelihood that Good Performance Will Be Repeated
################

amce.respondentvary.RepeatLikely <- amce(outcome_votechoice_binary ~ `Repeat Likely`:feat.dynasty + `Repeat Likely`:feat.gender +
                                           `Repeat Likely`:feat.gifts + `Repeat Likely`:feat.incumbent +     
                                           `Repeat Likely`:feat.lang +  `Repeat Likely`:feat.soc.orgs +   
                                           `Repeat Likely`:feat.village + `Repeat Likely`:feat.work,                
                                         data=conjoint.data[!is.na(conjoint.data$`Repeat Likely`),], 
                                         respondent.varying=c("`Repeat Likely`"), baselines=baselines, 
                                         cluster=TRUE, respondent.id="respondentID", design=conj.design.reweight)
summary(amce.respondentvary.RepeatLikely)


plot(amce.respondentvary.RepeatLikely, xlab="Change in Probability of Voting for a Candidate for Mayor",
     breaks=c(-.2, 0, .2), labels=c("-.2","0",".2"), text.size=8,
     label.baseline = TRUE, plot.display="interaction", attribute.names=c("Political Dynasty", "Gender", "Gifts in Campaign",
                                                                          "Incumbency Status", "Ethnicity/First Language",
                                                                          "Social Organizations", "Village", "Work/Wealth"))


################
################ Figure 4: Conjoint Results Conditional on Respondents’ Reported Beliefs That Incumbents Learn to Be Corrupt In Office
################

amce.respondentvary.learntobecorrupt <- amce(outcome_votechoice_binary ~ `Learn to be Corrupt`:feat.dynasty + `Learn to be Corrupt`:feat.gender +
                                               `Learn to be Corrupt`:feat.gifts + `Learn to be Corrupt`:feat.incumbent +     
                                               `Learn to be Corrupt`:feat.lang +  `Learn to be Corrupt`:feat.soc.orgs +   
                                               `Learn to be Corrupt`:feat.village + `Learn to be Corrupt`:feat.work,                
                                             data=conjoint.data[!is.na(conjoint.data$`Learn to be Corrupt`),], 
                                             respondent.varying=c("`Learn to be Corrupt`"), baselines=baselines, 
                                             cluster=TRUE, respondent.id="respondentID", design=conj.design.reweight)
summary(amce.respondentvary.learntobecorrupt)

plot(amce.respondentvary.learntobecorrupt, xlab="Change in Probability of Voting for a Candidate for Mayor",
     breaks=c(-.2, 0, .2), labels=c("-.2","0",".2"), text.size=8,
     label.baseline = TRUE, plot.display="interaction", attribute.names=c("Political Dynasty", "Gender", "Gifts in Campaign",
                                                                          "Incumbency Status", "Ethnicity/First Language",
                                                                          "Social Organizations", "Village", "Work/Wealth"))



###############################################################
####### Section Title: Mediating the Incumbency Bias
##############################################################

## dataset: RDD.data.heterogtxt

## each case is an OLS regression 
## municipal-level clustered standard errors using cluster.vcov()

library(multiwayvcov)
library(lmtest)


################
################ Table 1: RDD and Incumbent Re-election: Impact of Incumbent Performance
################

### CCT
reg.perf.juntos <- lm(won ~ won.prev*margin.voteshare.prev*juntos.new.district.final.norm,
                      data=RDD.data.heterogtxt)

coeftest(reg.perf.juntos, cluster.vcov(reg.perf.juntos, RDD.data.heterogtxt$UbigeoJNE))


### execution of budget for public works 

reg.perf.publicworks <- lm(won ~ won.prev*margin.voteshare.prev*publ.works.budget.spent.avg.norm, 
                           data=RDD.data.heterogtxt)

coeftest(reg.perf.publicworks, cluster.vcov(reg.perf.publicworks, RDD.data.heterogtxt$UbigeoJNE))


### Change in HDI 

reg.perf.HDI <- lm(won ~ won.prev*margin.voteshare.prev*HDI_Change.norm, 
                   data=RDD.data.heterogtxt)

coeftest(reg.perf.HDI, cluster.vcov(reg.perf.HDI, RDD.data.heterogtxt$UbigeoJNE))


### Survey - Satisfaction with municipal public management (only available in 2014)

reg.perf.2014distrmgmt <- lm(won ~ won.prev*margin.voteshare.prev*gestion.gob.distrital.2014.norm,
                             data=RDD.data.heterogtxt)

coeftest(reg.perf.2014distrmgmt, cluster.vcov(reg.perf.2014distrmgmt, RDD.data.heterogtxt$UbigeoJNE))



################
################ Table 2: RDD and Incumbent Re-election: Impact of Political Information
################

### Access to information technology

reg.polinfo <-  lm(won ~ won.prev*margin.voteshare.prev*comms.tech.index.norm,
                   data=RDD.data.heterogtxt)

coeftest(reg.polinfo, cluster.vcov(reg.polinfo, RDD.data.heterogtxt$UbigeoJNE))


### Survey: Self-report politically informed

reg.polinformed <-  lm(won ~ won.prev*margin.voteshare.prev*pol.informed.lag.norm,
                       data=RDD.data.heterogtxt)

coeftest(reg.polinformed, cluster.vcov(reg.polinformed, RDD.data.heterogtxt$UbigeoJNE))


### Survey: Self-report interested in politics

reg.polinterest <-  lm(won ~ won.prev*margin.voteshare.prev*pol.interest.lag.norm,
                       data=RDD.data.heterogtxt)

coeftest(reg.polinterest, cluster.vcov(reg.polinterest, RDD.data.heterogtxt$UbigeoJNE))


################
################ Table 3: RDD and Incumbent Re-election: Voter Trust in Institutions
################

### trust in horizontal accountability institutions

reg.trust.horiz <- lm(won ~ won.prev*margin.voteshare.prev*trust.horiz.avg.norm,
                      data=RDD.data.heterogtxt)

coeftest(reg.trust.horiz, cluster.vcov(reg.trust.horiz, RDD.data.heterogtxt$UbigeoJNE))


### trust in other politicians

reg.trust.pols <- lm(won ~ won.prev*margin.voteshare.prev*conf.politicians.avg.norm,
                     data=RDD.data.heterogtxt)

coeftest(reg.trust.pols, cluster.vcov(reg.trust.pols, RDD.data.heterogtxt$UbigeoJNE))


### trust in the police and army

reg.trust.policearmy <- lm(won ~ won.prev*margin.voteshare.prev*conf.police.army.avg.norm,
                           data=RDD.data.heterogtxt)

coeftest(reg.trust.policearmy, cluster.vcov(reg.trust.policearmy, RDD.data.heterogtxt$UbigeoJNE))


################
################ In text mention - Correlation between performance indicators and trust in horizontal oversight 
################

## dataset used: RDD.data.heterogtxt.district
# note: same as RDD.data.heterogtxt but with only one observation per district-year, 
# i.e. only district-level variables, not candidate-level

## correlations:

cor.test(RDD.data.heterogtxt.district$trust.horiz.avg, RDD.data.heterogtxt.district$publ.works.budget.spent.avg, use = "pairwise.complete.obs")
# 0.07795687 

cor.test(RDD.data.heterogtxt.district$trust.horiz.avg, RDD.data.heterogtxt.district$juntos.new.district.final, use = "pairwise.complete.obs")
# 0.01814257

cor.test(RDD.data.heterogtxt.district$trust.horiz.avg, RDD.data.heterogtxt.district$HDI_Change, use = "pairwise.complete.obs")
# 0.08990979 

cor.test(RDD.data.heterogtxt.district$trust.horiz.avg, RDD.data.heterogtxt.district$gestion.gob.distrital, use = "pairwise.complete.obs")
# 0.1198533


